package com.robot.agent.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.robot.agent.client.MerchantClient;
import com.robot.agent.client.OrdersClient;
import com.robot.agent.pojo.Agent;
import com.robot.agent.pojo.vo.Index;
import com.robot.agent.pojo.vo.IndexOrders;
import com.robot.agent.pojo.vo.IndexRevenue;
import com.robot.agent.pojo.vo.IndexStore;
import com.robot.agent.service.AgentService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * 首页
 *
 * @author lin
 */
@RestController
@CrossOrigin
@RequestMapping("/index")
public class IndexController {
    @Autowired
    private AgentService agentService;

    @Autowired
    private MerchantClient merchantClient;
    @Autowired
    private OrdersClient ordersClient;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private HttpServletRequest request;

    /**
     * agent表status状态 0-禁用 1-启用
     */
    private String agentStatusEnable = "1";
    int page = 1;
    int size = 10;

    /**
     * 首页店铺数
     *
     * @return
     */
    @GetMapping(value = "stores")
    public Result stores() {
        Claims claims = (Claims) request.getAttribute("robot_agent");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对代理商是否存在和状态进行判断

        IndexStore indexStore = new IndexStore();
        JSONObject yesterday = JSON.parseObject(merchantClient.thirdFindStoresByAgentIdAndYesterday(claims.getId(), page, size));
        JSONObject week = JSON.parseObject(merchantClient.thirdFindStoresByAgentIdAndWeek(claims.getId(), page, size));
        JSONObject total = JSON.parseObject(merchantClient.thirdFindStoresByAgentIdAndTotal(claims.getId(), page, size));
        if (yesterday == null) {
            logger.info("agentModule`s index call merchantModule failed");
            indexStore.setYesterday("0");
        } else {
            indexStore.setYesterday(yesterday.get("total").toString());
        }
        if (week == null) {
            logger.info("agentModule`s index call merchantModule failed");
            indexStore.setWeek("0");
        } else {
            indexStore.setWeek(week.get("total").toString());
        }
        if (total == null) {
            logger.info("agentModule`s index call merchantModule failed");
            indexStore.setTotal("0");
        } else {
            indexStore.setTotal(total.get("total").toString());
        }

        HashMap<String, Object> map = new HashMap<>(1);
        map.put("stores", indexStore);
        return new Result(StatusCode.SUCCESS_QUERY, map);
    }

    /**
     * 首页订单
     *
     * @return
     */
    @GetMapping(value = "orders")
    public Result orders() {
        Claims claims = (Claims) request.getAttribute("robot_agent");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对代理商是否存在和状态进行判断

        IndexOrders indexOrders = new IndexOrders();
        JSONObject yesterday = JSON.parseObject(ordersClient.thirdFindSubOrdersCountByAgentIdAndYesterday(claims.getId(), page, size));
        logger.info("agent yesterday SubOrders=" + yesterday);
        JSONObject week = JSON.parseObject(ordersClient.thirdFindSubOrdersCountByAgentIdAndWeek(claims.getId(), page, size));
        logger.info("agent week SubOrders=" + week);
        JSONObject total = JSON.parseObject(ordersClient.thirdFindSubOrdersCountByAgentIdAndTotal(claims.getId(), page, size));
        logger.info("agent total SubOrders=" + total);
        if (yesterday == null) {
            logger.info("agentModule`s index call ordersModule failed");
            indexOrders.setYesterday("0");
        } else {
            indexOrders.setYesterday(yesterday.get("total").toString());
        }
        if (week == null) {
            logger.info("agentModule`s index call ordersModule failed");
            indexOrders.setWeek("0");
        } else {
            indexOrders.setWeek(week.get("total").toString());
        }
        if (total == null) {
            logger.info("agentModule`s index call ordersModule failed");
            indexOrders.setTotal("0");
        } else {
            indexOrders.setTotal(total.get("total").toString());
        }

        HashMap<String, Object> map = new HashMap<>(1);
        map.put("orders", indexOrders);
        return new Result(StatusCode.SUCCESS_QUERY, map);
    }

    /**
     * 首页收益
     *
     * @return
     */
    @GetMapping(value = "revenue")
    public Result revenue() {
        Claims claims = (Claims) request.getAttribute("robot_agent");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对代理商是否存在和状态进行判断

        IndexRevenue indexRevenue = new IndexRevenue();
        JSONObject yesterday = JSON.parseObject(ordersClient.thirdFindSubOrdersCountByAgentIdAndYesterday(claims.getId(), page, size));
        logger.info("agent yesterday SubOrders=" + yesterday);
        JSONObject week = JSON.parseObject(ordersClient.thirdFindSubOrdersCountByAgentIdAndWeek(claims.getId(), page, size));
        logger.info("agent week SubOrders=" + week);
        JSONObject total = JSON.parseObject(ordersClient.thirdFindSubOrdersCountByAgentIdAndTotal(claims.getId(), page, size));
        logger.info("agent total SubOrders=" + total);
        if (yesterday == null) {
            logger.info("agentModule`s index call ordersModule failed");
            indexRevenue.setYesterday("0");
        } else {
            indexRevenue.setYesterday(yesterday.get("agentRevenue").toString());
        }
        if (week == null) {
            logger.info("agentModule`s index call ordersModule failed");
            indexRevenue.setWeek("0");
        } else {
            indexRevenue.setWeek(week.get("agentRevenue").toString());
        }
        if (total == null) {
            logger.info("agentModule`s index call ordersModule failed");
            indexRevenue.setTotal("0");
        } else {
            indexRevenue.setTotal(total.get("agentRevenue").toString());
        }

        HashMap<String, Object> map = new HashMap<>(1);
        map.put("revenue", indexRevenue);
        return new Result(StatusCode.SUCCESS_QUERY, map);
    }

    /**
     * 聚合的首页 
     *
     * @return
     */
    @GetMapping
    public Result index() {
        Claims claims = (Claims) request.getAttribute("robot_agent");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        Agent agentInDb = agentService.findById(claims.getId());
        if (agentInDb == null) {
            return new Result(StatusCode.ERROR_AGENT_DOES_NOTE_EXIST);
        }
        if (!agentStatusEnable.equals(agentInDb.getStatus())) {
            return new Result(StatusCode.ERROR_USER_INVALID);
        }

        Index yesterday = new Index();
        Index week = new Index();
        Index total = new Index();
        int page = 1;
        int size = 3;
        JSONObject yesterdayOrders = JSON.parseObject(ordersClient.thirdFindSubOrdersCountByAgentIdAndYesterday(agentInDb.getId(), page, size));
        logger.info("agent yesterday SubOrders=" + yesterday);
        JSONObject weekOrders = JSON.parseObject(ordersClient.thirdFindSubOrdersCountByAgentIdAndWeek(agentInDb.getId(), page, size));
        logger.info("agent week SubOrders=" + week);
        JSONObject totalOrders = JSON.parseObject(ordersClient.thirdFindSubOrdersCountByAgentIdAndTotal(agentInDb.getId(), page, size));
        logger.info("agent total SubOrders=" + total);
        //店铺数
        yesterday.setTotalStores(JSON.parseObject(merchantClient.thirdFindStoresByAgentIdAndYesterday(agentInDb.getId(), page, size)).get("total").toString());
        week.setTotalStores(JSON.parseObject(merchantClient.thirdFindStoresByAgentIdAndWeek(agentInDb.getId(), page, size)).get("total").toString());
        total.setTotalStores(JSON.parseObject(merchantClient.thirdFindStoresByAgentIdAndTotal(agentInDb.getId(), page, size)).get("total").toString());
        //订单数
        yesterday.setTotalOrders(yesterdayOrders.get("total").toString());
        week.setTotalOrders(weekOrders.get("total").toString());
        total.setTotalOrders(totalOrders.get("total").toString());
        //收益
        yesterday.setTotalRevenue(yesterdayOrders.get("agentRevenue").toString());
        week.setTotalRevenue(weekOrders.get("agentRevenue").toString());
        total.setTotalRevenue(totalOrders.get("agentRevenue").toString());

        HashMap<String, Object> map = new HashMap<>(3);
        map.put("total", total);
        map.put("yesterday", yesterday);
        map.put("week", week);
        return new Result(StatusCode.SUCCESS_QUERY, map);
    }
}
